//related to: WEBGL, CONTROLLER_JERARQUIA_SPACES, CONTROLLER_PAGE_STATE

//Asocia los handlers a los eventos del domContainer donde se renderiza WebGL
function DomContainerEventHandler(domContainerController, webglObj){

	var _domContainerController = domContainerController;
	var webglObject = webglObj;
	
	//variables 'para que ande' (estas estaban como variables de contexto en controller_webgl)
	var domContainer = webglObject.getDomContainer();//elemento DOM al que se le asociaran los handlers
	

	
	var patchDrag = 0; //DRAG - sin este patch, sigue sin andar bien :(
						//con este patch, entro a mousemove 1 de cada 5 veces
	
	//---------------------------------------------------------------------------------------------------------------------
	//---------------------------------- ASOCIAMOS EVENTOS A WINDOW ------------------------------------------------
	//---------------------------------------------------------------------------------------------------------------------
	function resizeWindow() { CONTROLLER_PAGE_STATE.resizeAll();};

	var resizeTimer = null;
	$(window).resize(function() {
	    clearTimeout(resizeTimer);
	    resizeTimer = setTimeout(resizeWindow, 300);//dispara el evento cada 300ms (sino crashea)
	});
	
	//---------------------------------------------------------------------------------------------------------------------
	//---------------------------------- ASOCIAR EVENTOS DOM CONTAINER ------------------------------------------------
	//---------------------------------------------------------------------------------------------------------------------
	//bindeamos funciones asociadas a los eventos del domContainer
	this.asociarEventosDomContainer = function(){
				
			var SELECTED;//, INTERSECTED;
			var offset = new THREE.Vector3();
			var inicial = null;
			
			var STATE = { NONE : -1, DRAG : 0, ROTATION : 1, BOTON_DERECHO : 2 }; //state se asigna dependiendo del boton con el que se clickee
			var STATE_NAME = {'-1' : 'none', 0 : 'drag', 1 : 'rotation', 2 : 'pan'};
			var x1 , y1 , x2 , y2 = null;
			var _state = STATE.NONE;
			
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ BLUR (lose FOCUS) +++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			$(domContainer).blur(function(){_state = STATE.NONE;});
			//$(domContainer).focus(function(){console.log('focus');});
			
			
			
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ MOUSE WHEEL +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//funcion para controlar los eventos de la rueda del mouse (jQuery Tools)
			$(domContainer).mousewheel(function(event, delta) {
				
				 CONTROLLER_PAGE_STATE.hideActiveSprite();//if(sprt) sprt.unselect();
				
				 if (isNaN(delta)) return;
				
				 var offsetDomContainer = $(domContainer).offset(); //a que distancia top y left se encuentra el contenedor
				 x1 = event.pageX - offsetDomContainer.left; //posicion relativa al contenedor
				 y1 = event.pageY - offsetDomContainer.top; //posicion relativa al contenedor
				
				 var x = (x1/$(domContainer).width())*2 - 1;
				 var y = ((y1/$(domContainer).height())*2 - 1)*-1;
				 
				 
				 //cada wrapper de escena, maneja el evento a su criterio
				 params = {};
				 params.type = 'mousewheel';
				 params.delta = delta;
				 params.x = x1;
				 params.y = y1;
				 params.xNorm = x;//entre -1 y 1
				 params.yNorm = y;//entre -1 y 1
				 
				 webglObject.activeWrapper().handleEvent(params);
				 //cada wrapper de escena, maneja el evento a su criterio
				 
				 
				
				//actualizamos el cursor
				if (delta>0){
					$(domContainer).css('cursor','url(css/cursors/zoomin.ico), none');
					setTimeout(function(){
						$(domContainer).css('cursor','');
					},750);
				}else{
					$(domContainer).css('cursor','url(css/cursors/zoomout.ico), none');
					setTimeout(function(){
						$(domContainer).css('cursor','');
					},750);
				}
			});
			
					
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ MOUSE DOWN +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			function mousedown( event ) {
				
				CONTROLLER_PAGE_STATE.hideActiveSprite();//deseleccionamos el sprite activo
				
				event.preventDefault();
				event.stopPropagation();
				
				if ( domContainer !== document ) {domContainer.focus();}
				
				if ( _state === STATE.NONE ) {
					
					_state = event.button;
				
				 	var offsetDomContainer = $(domContainer).offset(); //a que distancia top y left se encuentra el contenedor
				 	x1 = event.pageX - offsetDomContainer.left; //posicion relativa al contenedor
				 	y1 = event.pageY - offsetDomContainer.top; //posicion relativa al contenedor
				
				 	var x = (x1/$(domContainer).width())*2 - 1;
				 	var y = ((y1/$(domContainer).height())*2 - 1)*-1;
						
				 	
				 	
				 	//cada wrapper de escena, maneja el evento a su criterio
					 params = {};
					 params.type = 'mousedown';
					 params.x = x1;
					 params.y = y1;
					 params.xNorm = x;//entre -1 y 1
					 params.yNorm = y;//entre -1 y 1
					 
					 if ( _state === STATE.DRAG ) {
						 params.kind = 'drag';
					 }
					else if ( _state === STATE.ROTATION  ) {
						params.kind = 'rotation';
					}else if ( _state === STATE.BOTON_DERECHO){
						params.kind = 'boton_derecho';
					} 
					 
					 
					 var newState = webglObject.activeWrapper().handleEvent(params);
					 if (newState) _state = newState;
					 //cada wrapper de escena, maneja el evento a su criterio
				}

			};

			
			
			
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ MOUSE MOVE +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			function mousemove( event ) {
				
				//if ( _state === STATE.NONE ) {return;} 
				
				var offsetDomContainer = $(domContainer).offset(); //a que distancia top y left se encuentra el contenedor
				x2 = event.pageX - offsetDomContainer.left; //posicion relativa al contenedor
				y2 = event.pageY - offsetDomContainer.top;  //posicion relativa al contenedor
				
				 if (x1 == null || y1 == null){
					 x1 = x2; 
					 y1 = y2;
					// return;
				 }
				 
				//cada wrapper de escena, maneja el evento a su criterio
				 var x = (x2/$(domContainer).width())*2 - 1;
				 var y = ((y2/$(domContainer).height())*2 - 1)*-1;
				 
				 params = {};
				 params.type = 'mousemove';				
				 params.x = x2;
				 params.y = y2;
				 params.xNorm = x;//entre -1 y 1
				 params.yNorm = y;//entre -1 y 1
				 params.kind = 'no_button';
				 
				 var newState = webglObject.activeWrapper().handleEvent(params);
				 if (newState) _state = newState;
				//cada wrapper de escena, maneja el evento a su criterio
				 
				 
				//DRAG - sin este patch, sigue sin andar bien :(
					patchDrag++; 
					if (patchDrag % 7 == 0){patchDrag = 0;}
					else{return;}
				 
				if ( _state === STATE.DRAG) {
					$(domContainer).addClass('grabhand');
					$(domContainer).removeClass('hand');
					
					 params.kind = 'drag';
					 
				} else if ( _state === STATE.ROTATION  ) {

					$(domContainer).removeClass('grabhand');
					$(domContainer).removeClass('hand');
					$(domContainer).css("cursor",'move');
					
					params.kind = 'rotation';
					params.xOld = x1;
					params.yOld = y1;
				}else{
					//CONTROLLER_PAGE_STATE.hideActiveSprite();//deseleccionamos el sprite activo
				}
				
				var newState = webglObject.activeWrapper().handleEvent(params);
				
				 x1 = x2; 
				 y1 = y2;
				
				event.preventDefault();
				event.stopPropagation();

			};

			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ MOUSE UP +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			function mouseup( event ) {
				$(domContainer).css("cursor",'');
				$(domContainer).removeClass('grabhand');
						
				event.preventDefault();
				event.stopPropagation();
				
				
				 var offsetDomContainer = $(domContainer).offset(); //a que distancia top y left se encuentra el contenedor
				 var x2 = event.pageX - offsetDomContainer.left; //posicion relativa al contenedor
				 var y2 = event.pageY - offsetDomContainer.top;  //posicion relativa al contenedor
					 
				 var x = (x2/$(domContainer).width())*2 - 1;
				 var y = ((y2/$(domContainer).height())*2 - 1)*-1;
				 
				 
				//cada wrapper de escena, maneja el evento a su criterio
				 params = {};
				 params.type = 'mouseup';
				 params.x = x2;
				 params.y = y2;
				 params.xNorm = x;//entre -1 y 1
				 params.yNorm = y;//entre -1 y 1
				 webglObject.activeWrapper().handleEvent(params);
				//cada wrapper de escena, maneja el evento a su criterio
				 
				
				SELECTED = null;							
				x1 = null, y1 = null;
				_state = STATE.NONE;
			};
			
			function mouseout(event){
				$(domContainer).css("cursor",'');
				$(domContainer).removeClass('grabhand');
						
				if(event) event.preventDefault();	
			
				
				
				 var offsetDomContainer = $(domContainer).offset(); //a que distancia top y left se encuentra el contenedor
				 var x2 = event.pageX - offsetDomContainer.left; //posicion relativa al contenedor
				 var y2 = event.pageY - offsetDomContainer.top;  //posicion relativa al contenedor
					 
				 var x = (x2/$(domContainer).width())*2 - 1;
				 var y = ((y2/$(domContainer).height())*2 - 1)*-1;
				 
				 
				//cada wrapper de escena, maneja el evento a su criterio
				 params = {};
				 params.type = 'mouseout';
				 params.x = x2;
				 params.y = y2;
				 params.xNorm = x;//entre -1 y 1
				 params.yNorm = y;//entre -1 y 1
				 webglObject.activeWrapper().handleEvent(params);
				//cada wrapper de escena, maneja el evento a su criterio
				 
				
				SELECTED = null;							
				x1 = null, y1 = null;
				_state = STATE.NONE;
			}
				
			
			
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ KEY DOWN +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			function keyDown (event){
				CONTROLLER_PAGE_STATE.hideActiveSprite();
				
				
				//cada wrapper de escena, maneja el evento a su criterio
				 params = {};
				 params.type = 'keydown';
				 params.event = event;
				webglObject.activeWrapper().handleEvent(params);
				
				if (DIALOG_MANAGER.algunDialogoAbierto()) return;
				switch (event.keyCode){
					case 84: /*T*/
						var renderBool = webglObject.toggleRenderizar();
						CONTROLLER_PAGE_STATE.renderFromButton(renderBool);
						break;
					case 86: //V
						
						break;
					case 76 : //L
						WEBGL.mostrarEscena();
						break;
					case 74 : //J
						_domContainerController.toggleDataRenderer(); //muestra u oculta el panel con info del renderizado
						break;
					case 75 : //K
						actualizarInfo = true;//actualiza la info del renderizado
						break;
				}
			}
			
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ KEY DOWN +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			function keyUp (event){
				CONTROLLER_PAGE_STATE.hideActiveSprite();
				
				//cada wrapper de escena, maneja el evento a su criterio
				 params = {};
				 params.type = 'keyup';
				 params.event = event;
				 webglObject.activeWrapper().handleEvent(params);
			}
				
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			//++++++++++++++++++ RESIZE +++++++++++++++++++++++++
			//++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            $(domContainer).resize(function() {
            	webglObject.activeWrapper().handleEvent({type: 'resize'});
            });
			
			//bindeamos los eventos con sus funciones
			domContainer.addEventListener( 'keydown', keyDown,false);
			domContainer.addEventListener( 'keyup', keyUp, false );
			
			domContainer.addEventListener( 'mouseup', mouseup, false );
			domContainer.addEventListener( 'mouseout', mouseout, false );
			domContainer.addEventListener( 'mousemove', mousemove, false );
			domContainer.addEventListener( 'mousedown', mousedown, false );
			$(domContainer).bind('contextmenu', function(e){ return false;}); 
			
			
		}//fin 'asociarEventosDomContainer'
}/*fin objeto domEventHandler*/